<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\SDK\Captcha\V20230305\Models\VerifyIntelligentCaptchaRequest;
use AlibabaCloud\SDK\Captcha\V20230305\Captcha;
use Darabonba\OpenApi\Models\Config;

class AliVerify extends Base
{
    protected $table = 'user';
    protected $clientAlibabaCloud;

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);

        $aliVerifyConfig = config("ali_verify");
        $config = new Config([]);
        $config->accessKeyId = $aliVerifyConfig['accesskeyid'];
        $config->accessKeySecret = $aliVerifyConfig['accesskeysecret'];
        // 设置请求地址
        $config->endpoint = $aliVerifyConfig['endpoint'];
        // 设置连接超时为5000毫秒
        $config->connectTimeout = 5000;
        // 设置读超时为5000毫秒
        $config->readTimeout = 5000;
        // 初始化客户端
        $this->clientAlibabaCloud = new Captcha($config);
    }

    //发起认证请求
    public function verifyIntelligentCaptcha($captchaVerifyParam){
        if(empty($captchaVerifyParam)) {
            return false;
        }
        // 创建APi请求
        $request = new VerifyIntelligentCaptchaRequest([]);
        // 前端传来的验证参数 CaptchaVerifyParam
        $request->captchaVerifyParam = $captchaVerifyParam;
        // 发起请求
        try {
            $resp = $this->clientAlibabaCloud->verifyIntelligentCaptcha($request);
            // 建议使用您系统中的日志组件，打印返回
            // 获取验证码验证结果（请注意判空），将结果返回给前端。出现异常建议认为验证通过，优先保证业务可用，然后尽快排查异常原因。
            $captchaVerifyResult = $resp->body->result->verifyResult;
        }
        catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
                write_log('error_aliVerify', 'verifyIntelligentCaptcha', ['error'=>$error]);
            }
            $captchaVerifyResult = true;
        }
        return $captchaVerifyResult;
    }
} 
